package com.changzhi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changzhi.agora.AgoraUtil;
import com.changzhi.common.constans.RedisConstans;
import com.changzhi.common.constants.RedisConstants;
import com.changzhi.common.enums.*;
import com.changzhi.common.exception.ServiceException;
import com.changzhi.common.util.DateUtil;
import com.changzhi.common.util.MD5Util;
import com.changzhi.ldyl.model.*;
import com.changzhi.ldyl.model.dto.PrizeDto;
import com.changzhi.ldyl.model.vo.RechargeGiftVo;
import com.changzhi.mapper.*;
import com.changzhi.service.*;
import com.changzhi.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huangrc
 * @since 2020-11-26
 */
@Slf4j
@Service
public class OrderDayServiceImpl extends ServiceImpl<OrderDayMapper, OrderDay> implements OrderDayService {

	@Resource
	private OrderDayMapper orderDayMapper;
	@Resource
	private UserInvitationAwardMapper userInvitationAwardMapper;
	@Resource
	private UserInvitationConfigMapper userInvitationConfigMapper;
	@Autowired
	private InviteService inviteService;

	@Resource
	private UserLoginLogMapper userLoginLogMapper;

	@Resource
	private PaymentOrderMapper paymentOrderMapper;

	@Resource
	private UserGiftBackpackMapper userGiftBackpackMapper;

	@Resource
	private FirstRechargeRecordMapper firstRechargeRecordMapper;

	@Resource
	private FirstRechargeAwardMapper firstRechargeAwardMapper;

	@Resource
	private UserMessageMapper userMessageMapper;

	@Autowired
	private RedisUtil redisUtil;

	@Resource
	private UserDressUpMapper userDressUpMapper;

	@Resource
	private UserService userService;

	@Resource
	private SysDictMapper sysDictMapper;

	@Resource
	private OfficalMsgRecordMapper officalMsgRecordMapper;

	@Resource
	private SysDictService sysDictService;

	@Resource
	private I18nTextMapper i18nTextMapper;

	@Resource
	private UserFollowersMapper userFollowersMapper;

	@Resource
	private UserFollowMapper userFollowMapper;

	@Resource
	private PrivateChatMsgService privateChatMsgService;


	public final static DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");

	private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

	@Override
	public void doMqDataByOrderSuccess(String msg) {
		executorService.schedule(()->{
			PaymentOrder paymentOrder = JSON.parseObject(msg, PaymentOrder.class);
			if(paymentOrder == null){
				return;
			}
			//查询当天该用户订单金额
			LocalDate createDate = paymentOrder.getCreateTime().toLocalDate();
			OrderDay priceData = orderDayMapper.getTotalPrice(paymentOrder.getCliBuyerId(), createDate);
			//查询数据是否存在
			LambdaQueryWrapper<OrderDay> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(OrderDay::getUserId, paymentOrder.getCliBuyerId()).eq(OrderDay::getCreateDate, createDate);
			OrderDay orderDb = orderDayMapper.selectOne(wrapper);
			//存在则更新，不存在则插入
			OrderDay record = new OrderDay();
			record.setCliPrice(priceData.getCliPrice());
			record.setComputePrice(priceData.getComputePrice());
			record.setDiamondsAmount(priceData.getDiamondsAmount());
			if (orderDb == null) {
				record.setUserId(paymentOrder.getCliBuyerId());
				record.setCreateDate(createDate);
				record.setBindChannelId(getBindChannelId(paymentOrder.getCliBuyerId()));
				orderDayMapper.insert(record);
			} else{
				record.setId(orderDb.getId());
				orderDayMapper.updateById(record);
			}
			//充值超100元，邀请加友情币
			executorService.schedule(()->{
				inviteService.doInviteByOrderSuccess(paymentOrder.getCliBuyerId());
			}, 1, TimeUnit.SECONDS);

		}, 1, TimeUnit.SECONDS);
	}

	//是否首天
	private Integer getFirstDay(String userId, LocalDate createDate){
		Integer firstDay = 0;
		LambdaQueryWrapper<OrderDay> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.eq(OrderDay::getUserId, userId);
		queryWrapper.orderByAsc(OrderDay::getCreateDate).last("limit 1");
		OrderDay orderDay = orderDayMapper.selectOne(queryWrapper);
		if(orderDay == null || orderDay.getCreateDate().isEqual(createDate)){
			firstDay = 1;
		}
		return firstDay;
	}

	private String getBindChannelId(String userId){
		//邀请查询
		String inviterUserId = "";
		LambdaQueryWrapper<UserInvitationAward> inviteWrapper = new LambdaQueryWrapper<>();
		inviteWrapper.eq(UserInvitationAward::getUserId, userId).last("limit 1");
		UserInvitationAward invitationAward = userInvitationAwardMapper.selectOne(inviteWrapper);
		if (invitationAward != null && invitationAward.getInviterUserId() != null) {
			if(StringUtils.isNotBlank(invitationAward.getSkipChannelId())){
				return invitationAward.getSkipChannelId();
			}
			inviterUserId = invitationAward.getInviterUserId();
		}
		//跳转房间查询
		String bindChannelId = "";
		if(StringUtils.isNotBlank(inviterUserId)){
			LambdaQueryWrapper<UserInvitationConfig> configWrapper = new LambdaQueryWrapper<>();
			configWrapper.eq(UserInvitationConfig::getUserId, invitationAward.getInviterUserId()).last("limit 1");
			UserInvitationConfig invitationConfig = userInvitationConfigMapper.selectOne(configWrapper);
			if (invitationConfig != null && StringUtils.isNotBlank(invitationConfig.getSkipChannelId())) {
				bindChannelId = invitationConfig.getSkipChannelId();
			}
		}
		return bindChannelId;
	}

	@Override
	public void repairOrder(String startDateStr, String endDateStr) {
		LocalDate startDate = StringUtils.isBlank(startDateStr) ? LocalDate.now().minusDays(1) : DateUtil.stringToLocalDate(startDateStr);
		LocalDate endDate = StringUtils.isBlank(endDateStr) ? LocalDate.now() : DateUtil.stringToLocalDate(endDateStr);
		while (startDate.isEqual(endDate) || startDate.isBefore(endDate)){
			repairOrderData(startDate);
			startDate = startDate.plusDays(1);
		}
	}

	@Override
	public void sendFirstRechargeAward(String msg) {
		executorService.schedule(()->{
			PaymentOrder paymentOrder = JSON.parseObject(msg, PaymentOrder.class);
			if(paymentOrder == null){
				return;
			}
			log.info("检查首冲逻辑，订单信息：{}",msg);
			UserLoginLog userLoginLog = userLoginLogMapper.selectOne(new QueryWrapper<UserLoginLog>().lambda().eq(UserLoginLog::getUserId, paymentOrder.getCliBuyerId()).orderBy(true,false,UserLoginLog::getCreateTime).last("limit 1"));
			//查当前设备的首条订单
			PaymentOrder fristOrder = getFirstOrder(userLoginLog);
			//首冲
			if(null != fristOrder && fristOrder.getOrderNo().equals(paymentOrder.getOrderNo())){
				sendFirstRechageAward(fristOrder,paymentOrder.getCliBuyerId(),userLoginLog);
			}
		}, 1, TimeUnit.SECONDS);
	}

	private void sendOfficalChargeMsg(User user){
		OfficalMsgRecord record = new OfficalMsgRecord();
		String lang = user.getLang();
		record.setUserId(user.getUserId());
		record.setCreateTime(LocalDateTime.now());
		Map<String, String> chargeMsgI18n = getChargeMsgI18n();
		log.info("查询18N消息：I18nMap:{}" ,JSONObject.toJSONString(chargeMsgI18n));
		if(chargeMsgI18n.containsKey(lang)){
			record.setLang(lang);
			record.setText(chargeMsgI18n.get(lang));
		}else{
			 lang = "zh_TW";
			if(chargeMsgI18n.containsKey(lang)) {
				record.setLang(lang);
				record.setText(chargeMsgI18n.get(lang));
			}else{
				//没有默认语言放弃
				return;
			}
		}
		//获取文本后准备发送消息
		if(StringUtils.isNotBlank(record.getLang()) &&StringUtils.isNotBlank(record.getText()) ){
			User user10000 = userService.getUserByAccountId(10000);
			if (null == user10000) {
				log.error("sendOfficalChargeMsg====10000号不存在");
			} else {
				log.info("点对点消息发送开始：用户id：{}",user.getUserId());

				PrivateChatMsg msg = new PrivateChatMsg();
				String privateChannelId;
				if (user10000.getUserId().compareTo(user.getUserId()) > 0) {
					privateChannelId = user10000.getUserId() + user.getUserId();
				} else {
					privateChannelId = user.getUserId() + user10000.getUserId();
				}
				privateChannelId = MD5Util.getMD5Str(privateChannelId);
				msg.setPrivateChannelId(privateChannelId);
				msg.setSpeakerUserId(user10000.getUserId());
				msg.setSpeakerAccountId(user10000.getAccountId());
				msg.setListenerUserId(user.getUserId());
				msg.setListenerAccountId(user.getAccountId());
				msg.setContent(record.getText()); // 需要将原始内容保存到数据库
				msg.setStatus(1);
				msg.setCreateTime(LocalDateTime.now());
				privateChatMsgService.save(msg);

				AgoraUtil.peerMessages(user10000.getUserId(),user.getUserId(),record.getText());
				log.info("点对点消息发送结束");
				//保存发送记录
				officalMsgRecordMapper.insert(record);
			}
		}
	}

	/**
	 * 获取国际化语言信息
	 * @return
	 */
	private Map<String,String> getChargeMsgI18n(){
		Map<String,String> i18nMap = null;
		if (redisUtil.hasKey(RedisConstans.PAYMENT_OFFICALCHARGEMSGI18N)) {
			i18nMap = redisUtil.get(RedisConstans.PAYMENT_OFFICALCHARGEMSGI18N);
		}else{
			i18nMap = new HashMap<>();
			//默认数据
			String textCN = "基于您良好的充值记录，为您开通了VIP客户专属充值服务：\n" +
					"1.联系官方客服賴Line：hearlive，人工充值；\n" +
					"2.或在官网自助下单：https://www.hearlive.net/\n" +
					"上述2种方式比应用内充值多出约20%的钻石！";
			i18nMap.put(LangEnum.ZH_CN.getLang(),textCN);
			String textTW = "基於您良好的充值記錄，為您開通了VIP客戶專屬充值服務：\n" +
					"1.聯繫官方客服賴Line：hearlive，人工充值；\n" +
					"2.或在官網自助下單：https://www.hearlive.net/\n" +
					"上述2種方式比應用內充值多出約20%的鑽石！";
			i18nMap.put(LangEnum.ZH_TW.getLang(),textTW);
			String textEN = "Based on your good recharge record, we have opened exclusive recharge service for VIP customers for you:\n" +
					"1. Contact official customer service lai-line: hearlive, and recharge manually;\n" +
					"2. Or place an order on the official website: https://www.hearlive.net/\n" +
					"The above two ways than the application in the top up about 20% of the diamond!";
			i18nMap.put(LangEnum.EN_US.getLang(),textEN);

			//数据库读取覆盖
			LambdaQueryWrapper<I18nText> i18nWrapper = new QueryWrapper<I18nText>().lambda()
					.eq(I18nText::getType, I18nTextTypeEnum.officalChargeMsg);
			List<I18nText> i18nTexts = i18nTextMapper.selectList(i18nWrapper);
			for (I18nText i18nText : i18nTexts) {
				i18nMap.put(i18nText.getLang(),i18nText.getText());
			}
			redisUtil.set(RedisConstans.PAYMENT_OFFICALCHARGEMSGI18N,i18nMap,RedisConstans.FIVE_MINUTES);

		}
		return i18nMap;
	}


	@Override
	public void checkUserPaymentChannel(String msg) {
		log.info("监测是否需要发送官方充值消息");
		PaymentOrder paymentOrder = JSON.parseObject(msg, PaymentOrder.class);
		//已经存在这个key则说明用户不用继续检查
		if (redisUtil.hHasKey(RedisConstans.PAYMENT_OFFICALCHARGEMSG,paymentOrder.getCliBuyerId())) {
			log.info("不需要发送消息");
			return ;
		}
		//查询用户数据
		User user = userService.getUser(paymentOrder.getCliBuyerId());
		if(null == user){
			log.info("用户数据为空");
			return ;
		}
		//查询配置参数
		SysDict officalChargeMsg = sysDictService.getSysDictByCache("officalChargeMsg", RedisConstans.FIVE_MINUTES);
		Integer msgLimit = 1; Integer orderLimit = 3;String targetRegion="TW,HK,MC";
		String checkPayMent = "300,310"; String oficalPayments = "320,500";
		if(null != officalChargeMsg){
			if(StringUtils.isNotBlank(officalChargeMsg.getProperty1())){
				orderLimit = Integer.valueOf(officalChargeMsg.getProperty1());
			}
			if(StringUtils.isNotBlank(officalChargeMsg.getProperty2())){
				targetRegion = officalChargeMsg.getProperty2();
			}
			if(StringUtils.isNotBlank(officalChargeMsg.getProperty3())){
				msgLimit = Integer.valueOf(officalChargeMsg.getProperty3());
			}
			if(StringUtils.isNotBlank(officalChargeMsg.getProperty4())){
				checkPayMent = officalChargeMsg.getProperty4();
			}
			if(StringUtils.isNotBlank(officalChargeMsg.getProperty5())){
				oficalPayments = officalChargeMsg.getProperty5();
			}
		}
		//非指定地区不需要检查
		List<String> targetRegionList = Arrays.asList(targetRegion.split(","));
		if(!targetRegionList.contains(user.getCountry())){
			log.info("不是指定国家");
			return ;
		}
		//查看是否已经超过指定消息数量
		LambdaQueryWrapper<OfficalMsgRecord> recordLambdaQueryWrapper = new QueryWrapper<OfficalMsgRecord>().lambda()
				.eq(OfficalMsgRecord::getUserId,paymentOrder.getCliBuyerId());
		Integer MsgCount = officalMsgRecordMapper.selectCount(recordLambdaQueryWrapper);
		if(MsgCount >= msgLimit){
			//添加缓存
			redisUtil.hset(RedisConstans.PAYMENT_OFFICALCHARGEMSG,paymentOrder.getCliBuyerId(),1,RedisConstans.ONE_HOUR);
			return ;
		}

		//查询一下官方充值数量
		LambdaQueryWrapper<PaymentOrder> orderQueryWrapper = new QueryWrapper<PaymentOrder>().lambda()
				.eq(PaymentOrder::getCliBuyerId,paymentOrder.getCliBuyerId()).eq(PaymentOrder::getOrderStatus, OrderStatusTypeEnum.OTHER_SUCCESS)
				.in(PaymentOrder::getPayChannelType,oficalPayments.split(","));
		Integer payCountInOfficalCharge = paymentOrderMapper.selectCount(orderQueryWrapper);
		//已经使用过官方充值渠道，不需要继续监测
		if(payCountInOfficalCharge >= 1){
			//添加缓存
			redisUtil.hset(RedisConstans.PAYMENT_OFFICALCHARGEMSG,paymentOrder.getCliBuyerId(),1,RedisConstans.ONE_HOUR);
			return ;
		}

		//查一个直充数量
		 orderQueryWrapper = new QueryWrapper<PaymentOrder>().lambda()
				.eq(PaymentOrder::getCliBuyerId,paymentOrder.getCliBuyerId()).eq(PaymentOrder::getOrderStatus, OrderStatusTypeEnum.OTHER_SUCCESS)
				.in(PaymentOrder::getPayChannelType,checkPayMent.split(","));
		Integer payCountInAppCharge = paymentOrderMapper.selectCount(orderQueryWrapper);

		if(payCountInAppCharge >= orderLimit ){
			//直充条件满足，发送消息并且保存记录
			sendOfficalChargeMsg(user);
		}

	}

	@Override
	public void checkAccount10000Follower(String msg) {
		log.info("检查一万号关注");
		PaymentOrder paymentOrder = JSON.parseObject(msg, PaymentOrder.class);
		if(paymentOrder == null){
			return;
		}
		User userTarget = userService.getUser(paymentOrder.getCliBuyerId());
		//添加关注一万号
		User user10000 = userService.getUserByAccountId(10000);
		if(null == userTarget || null == user10000){
			return ;
		}
		UserFollow follow10000  = genUserFollow(userTarget,user10000);
		userFollowMapper.insertOrUpdate(follow10000);

		UserFollowers followers10000 =  genUserFollowers(user10000,userTarget);
		userFollowersMapper.insertOrUpdate(followers10000);

		//添加一万号关注
		 follow10000  = genUserFollow(user10000,userTarget);
		userFollowMapper.insertOrUpdate(follow10000);
		 followers10000 =  genUserFollowers(userTarget,user10000);
		userFollowersMapper.insertOrUpdate(followers10000);

		//更新双方关注数据
		userTarget.setFollowing(userFollowMapper.getFollowingCount(userTarget.getUserId()));// 执行关注的人关注数量
		user10000.setFollowers(userFollowersMapper.getFollowersCount(user10000.getUserId()));// 被关注的人粉丝数量

		user10000.setFollowing(userFollowMapper.getFollowingCount(user10000.getUserId()));// 执行关注的人关注数量
		userTarget.setFollowers(userFollowersMapper.getFollowersCount(userTarget.getUserId()));// 被关注的人粉丝数量

		userTarget.setFriend(userFollowMapper.getFriend(userTarget.getUserId()));
		user10000.setFriend(userFollowersMapper.getFriend(user10000.getUserId()));

		userService.updateUser(userTarget);
		userService.updateUser(user10000);
		log.info("检查一万号关注结束");

	}

	private UserFollowers genUserFollowers(User user,User userTarget){
		UserFollowers userFollow = new UserFollowers();
		userFollow.setUserId(user.getUserId());
		userFollow.setFollowedUserId(userTarget.getUserId());
		userFollow.setNickname(userTarget.getNickname());
		userFollow.setAvatarUrl(userTarget.getAvatarUrl());
		userFollow.setGender(userTarget.getGender());
		userFollow.setCreateTime(LocalDateTime.now());
		userFollow.setBothStatus(2);
		return userFollow;
	}

	private UserFollow genUserFollow(User user,User userTarget){
		UserFollow userFollow = new UserFollow();
		userFollow.setUserId(user.getUserId());
		userFollow.setFollowingUserId(userTarget.getUserId());
		userFollow.setNickname(userTarget.getNickname());
		userFollow.setAvatarUrl(userTarget.getAvatarUrl());
		userFollow.setGender(userTarget.getGender());
		userFollow.setCreateTime(LocalDateTime.now());
		userFollow.setBothStatus(2);
		return userFollow;
	}

	private PaymentOrder getFirstOrder(UserLoginLog userLoginLog){
		PaymentOrder fristOrder = null;
//		String key = RedisConstants.PAYMENT_FIRSTRECHARGE + getDeviceKey(userLoginLog) ;
//		if(redisUtil.hasKey(key)){
//			fristOrder =  redisUtil.get(key);
//		}else{
			fristOrder = paymentOrderMapper.getSuccessFirstOrdersByUserId(userLoginLog.getUserId());
//			if(null != fristOrder){
//				redisUtil.set(key,fristOrder,RedisConstants.HALF_OF_HOUR);
//			}
//		}
		return fristOrder;
	}

	private void sendFirstRechageAward(PaymentOrder fristOrder,String userId,UserLoginLog userLoginLog){
		// 获取奖品信息
		log.info("首冲奖励发放开始，userId：{},userLoginLog:{}",userId,userLoginLog);
		FirstRechargeRecord firstRechargeRecord = firstRechargeRecordMapper.selectOne(new QueryWrapper<FirstRechargeRecord>().lambda().eq(FirstRechargeRecord::getUserId, userId).last("limit 1"));
		if(null == firstRechargeRecord){
			LambdaQueryWrapper<FirstRechargeRecord> last = new QueryWrapper<FirstRechargeRecord>().lambda();
			if(0 == userLoginLog.getOs()){
				last.eq(FirstRechargeRecord::getDeviceId, userLoginLog.getAndroidId());
			}else{
				last.eq(FirstRechargeRecord::getDeviceId, userLoginLog.getDeviceId());
			}
			last.eq(FirstRechargeRecord::getOs, userLoginLog.getOs()).last("limit 1");
			firstRechargeRecord = firstRechargeRecordMapper.selectOne(last);
		}
		log.info("首冲奖励发放开始，firstRechargeRecord:{}", JSONObject.toJSONString(firstRechargeRecord));
		if(null == firstRechargeRecord){
			firstRechargeRecord = genRechargeRecord( userLoginLog, fristOrder, userId);
		}
		if(0 == firstRechargeRecord.getRechargeStatus()){
			if(2 == firstRechargeRecord.getProcessStep()){
				return ;
			}
			//没有点击过开宝箱
			if(0 == firstRechargeRecord.getProcessStep()){
				openChargeGiftBox( userLoginLog, firstRechargeRecord);
			}
			sendChargeGifts( firstRechargeRecord, userLoginLog, userId);
		}

	}

	private void sendChargeGifts(FirstRechargeRecord firstRechargeRecord,UserLoginLog userLoginLog,String userId){
		String key = RedisConstans.ACTIVITY_FIRSTRECHARGET_DEVICE + getDeviceKey(userLoginLog);
		long incr = redisUtil.incr(key,1,RedisConstans.ONE_DAY);
		if(incr == 1 ){
			firstRechargeRecord.setUserId(userId);
			firstRechargeRecord.setProcessStep(2);
			firstRechargeRecord.setRechargeTime(LocalDateTime.now());
			firstRechargeRecord.setRechargeStatus(1);
			LambdaUpdateWrapper<FirstRechargeRecord> lamq = new UpdateWrapper<FirstRechargeRecord>().lambda();
			if(0 == userLoginLog.getOs()){
				lamq.eq(FirstRechargeRecord::getDeviceId, userLoginLog.getAndroidId());
			}else{
				lamq.eq(FirstRechargeRecord::getDeviceId, userLoginLog.getDeviceId());
			}
			lamq.eq(FirstRechargeRecord::getOs,userLoginLog.getOs());
			lamq.eq(FirstRechargeRecord::getProcessStep, 1).eq(FirstRechargeRecord::getRechargeStatus, 0);

			int update = firstRechargeRecordMapper.update(firstRechargeRecord, lamq);
			log.info("首冲奖励发放开始，update:{}", update);
			if(update > 0 ){
				List<RechargeGiftVo> gifts = firstRechargeRecordMapper.getFirstRechargeAwardById(firstRechargeRecord.getId());
				log.info("首冲奖励发放中本轮礼物信息为，gifts:{}", JSONObject.toJSONString(gifts));
				RechargeGiftVo giftConfig = null;
				if(gifts.size() > 0 ){
					for (int i = 0; i < gifts.size(); i++) {
						giftConfig = gifts.get(i);
						if(GiftTypeEnum.DRESS_UP.getValue()== giftConfig.getGiftType()){
							saveUserDress(userId,giftConfig.getDressId(),giftConfig.getGiftNum());
						}else{
							for (int y = 0; y < giftConfig.getGiftNum(); y++) {
								UserGiftBackpack backpack = new UserGiftBackpack();
								backpack.setUserId(userId);
								backpack.setGiftId(giftConfig.getId());
								backpack.setName(giftConfig.getName());
								backpack.setValue(giftConfig.getValue());
								backpack.setIconUrl(giftConfig.getIconUrl());
								backpack.setEffects(giftConfig.getEffects());
								backpack.setLovenum(giftConfig.getLovenum());
								backpack.setStatus(0);
								backpack.setSource(3);
								backpack.setGiftType(giftConfig.getGiftType());
								userGiftBackpackMapper.insert(backpack);
							}
						}

					}
					firstRechargeAwardMapper.updateAward( firstRechargeRecord.getId());
					redisUtil.hdel(RedisConstans.USER_RECHARGESTATUS, getDeviceKey(userLoginLog));
					redisUtil.del(RedisConstans.USER_RECHARGEGIFTS);
					sendAwardMsg(firstRechargeRecord);
				}

			}
		}
	}


	public void saveUserDress(String userId,Integer dressUpId,Integer multiple) {
		if (userId == null) {
			log.error("首冲奖励---用户Id不能为空");
			return;
		}
		if (dressUpId == null) {
			log.error("首冲奖励--装扮名称不能为空");
			return;
		}
		SysDict sysDict = sysDictMapper.selectById(dressUpId);
		if (sysDict == null) {
			log.error("首冲奖励--装扮不存在");
			return ;
		}
		User user = userService.getUser(userId);
		if (user == null) {
			log.error("首冲奖励--用户不存在");
			return ;
		}
		//判断是否是否存在
		boolean existDressUp = userDressUpMapper.isExistDressUp(user.getUserId(), dressUpId);
		//增加天数
		Integer duration =  StringUtils.isBlank(sysDict.getProperty4()) ? 0 : Integer.valueOf(sysDict.getProperty4()) * multiple;
		if(existDressUp){
			//增加时长
			userDressUpMapper.updateChargeGiftDressUpTime(userId, dressUpId, duration);
		}else{
			LocalDateTime now = LocalDateTime.now();
			UserDressUp userDressUp = new UserDressUp();
			userDressUp.setUserId(userId);
			userDressUp.setType(Integer.valueOf(sysDict.getProperty1()));
			userDressUp.setDressId(sysDict.getId());
			userDressUp.setPrice(Integer.valueOf(sysDict.getProperty5()));
			userDressUp.setStatus(0);
			userDressUp.setDuration(duration);
			userDressUp.setLimitedType(Integer.valueOf(sysDict.getProperty7()));
			userDressUp.setCreateTime(now);
			userDressUp.setEffectiveTime(LocalDateTime.now());
			if(duration > 0 ){
				userDressUp.setExpireTime(LocalDateTime.now().plusDays(duration));
			}
			userDressUp.setUpdateTime(now);
			userDressUpMapper.insert(userDressUp);
		}
	}
	private void openChargeGiftBox(UserLoginLog userLoginLog,FirstRechargeRecord firstRechargeRecord){
		String key = RedisConstants.USER_OPENRECHARGEBOXFLAG + getDeviceKey(userLoginLog);
		long incr = redisUtil.incr(key, 1,RedisConstants.ONE_DAY);
		if(1 == incr){
			firstRechargeRecordMapper.genRechargeGiftAward(firstRechargeRecord.getId());
			firstRechargeRecord.setProcessStep(1);
			firstRechargeRecordMapper.updateById(firstRechargeRecord);
		}
	}

	private FirstRechargeRecord genRechargeRecord(UserLoginLog userLoginLog, PaymentOrder fristOrder, String userId){
		//没有领过奖品直接发放
		FirstRechargeRecord firstRechargeRecord = new FirstRechargeRecord();
		firstRechargeRecord.setCreateTime(LocalDateTime.now());
		firstRechargeRecord.setOs(userLoginLog.getOs());
		if(0 == userLoginLog.getOs()){
			firstRechargeRecord.setDeviceId(userLoginLog.getAndroidId());
		}else{
			firstRechargeRecord.setDeviceId(userLoginLog.getDeviceId());
		}
		firstRechargeRecord.setUserId(userId); //设置领奖用户ID
		firstRechargeRecord.setRechargeStatus(0);
		firstRechargeRecord.setRechargeTime(fristOrder.getCreateTime());
		firstRechargeRecord.setProcessStep(0);
		firstRechargeRecordMapper.insert(firstRechargeRecord);

		return firstRechargeRecord;
	}

	private String getDeviceKey(UserLoginLog userLoginLog){
		String key = null;
		if(0 == userLoginLog.getOs()){
			key =  userLoginLog.getOs() + "_" + userLoginLog.getAndroidId();
		}else{
			key =  userLoginLog.getOs() + "_" + userLoginLog.getDeviceId();
		}
		return key;
	}

	private void sendAwardMsg(FirstRechargeRecord record){
		UserMessage message = new UserMessage();
		message.setUserId(record.getUserId());
		message.setTargetUserId(record.getUserId());
		message.setNickname("首充獎勵到賬通知");
		message.setRecordType(0);
		message.setMsgType(1);
		message.setMsgContent("您好，您的首充獎勵已經到賬，請檢查您的揹包");
		message.setCreateTime(LocalDateTime.now());
		message.setUpdateTime(LocalDateTime.now());
		message.setMsgTargetId(record.getId() + "");
		userMessageMapper.insert(message);

	}


	/*@Override
	public void repairFirstOrder(String startDateStr, String endDateStr) {
		LocalDate startDate = StringUtils.isBlank(startDateStr) ? LocalDate.now().minusDays(1) : DateUtil
				.stringToLocalDate(startDateStr);
		LocalDate endDate = StringUtils.isBlank(endDateStr) ? LocalDate.now() : DateUtil.stringToLocalDate(endDateStr);
		while (startDate.isEqual(endDate) || startDate.isBefore(endDate)){
			long start = System.currentTimeMillis();
			log.info("methodName:repairFirstOrder,当前日期={}，修复开始",startDate.toString());
			//检查是否需要更新
			List<PaymentOrder> orders = orderDayMapper.getFirstOrderPriceList(startDate);
			for (PaymentOrder order : orders) {
				LambdaQueryWrapper<FirstOrder> wrapper = new LambdaQueryWrapper<>();
				wrapper.eq(FirstOrder::getUserId, order.getCliBuyerId());
				FirstOrder firstOrder = firstOrderMapper.selectOne(wrapper);
				if (firstOrder != null && firstOrder.getCliPrice().intValue() != 0) {
					continue;
				}
				PaymentOrder paymentOrder = orderDayMapper.getFirstOrderPrice(order.getCliBuyerId());
				if(paymentOrder == null || paymentOrder.getCliPrice() == null){
					continue;
				}
				FirstOrder record = new FirstOrder();
				record.setUserId(order.getCliBuyerId());
				record.setCliPrice(paymentOrder.getCliPrice());
				record.setComputePrice(paymentOrder.getCliPrice().multiply(new BigDecimal(0.7)));
				record.setCreateTime(paymentOrder.getCreateTime());
				orderDayMapper.replaceIntoFirstOrder(record);
				log.warn("methodName:repairFirstOrder,问题数据修复={}",JSON.toJSONString(record));
			}
			log.warn("methodName:repairFirstOrder,当前日期={},耗时={},修复完成...",startDate.toString(),System.currentTimeMillis() - start);
			startDate = startDate.plusDays(1);
		}
	}*/

	private void repairOrderData(LocalDate localDate){
		long start = System.currentTimeMillis();
		log.info("methodName:repairOrderData,当前日期={}，修复开始",localDate.toString());
		repairOrderByNoCompute(localDate);
		log.info("methodName:repairOrderData,当前日期={},耗时={},修复完成...",localDate.toString(),System.currentTimeMillis() - start);
	}


	//修复价格为0的异常订单数据
	private void repairOrderByZero(LocalDate localDate){
		List<OrderDay> list = orderDayMapper.getPriceByZero(localDate);
		if(CollectionUtils.isEmpty(list)){
			return;
		}
		log.error("methodName:repairOrderData,问题数据条数={},list={}",list.size(),JSON.toJSONString(list));
		for (OrderDay orderDay : list) {
			OrderDay priceData = orderDayMapper.getTotalPrice(orderDay.getUserId(), orderDay.getCreateDate());
			OrderDay record = new OrderDay();
			record.setUserId(orderDay.getUserId());
			record.setCreateDate(orderDay.getCreateDate());
			record.setCliPrice(priceData.getCliPrice());
			record.setComputePrice(priceData.getComputePrice());
			record.setBindChannelId(getBindChannelId(orderDay.getUserId()));
			//record.setFirst(getFirstDay(orderDay.getUserId(), orderDay.getCreateDate()));
			orderDayMapper.replaceOrderDay(record);
		}
	}

	//修复没有计算到的异常订单数据
	private void repairOrderByNoCompute(LocalDate localDate){
		String dateStr = localDate.format(fmt);
		String startTime = dateStr + " 00:00:00";
		String endTime= dateStr + " 23:59:59";
		//检查是否需要更新
		Double totalPrice = orderDayMapper.compareOrderTotalPrice(localDate, startTime, endTime);
		Integer totalDiamonds = orderDayMapper.compareOrderTotalDiamonds(localDate, startTime, endTime);
		if((totalPrice == null || totalPrice == 0) && (totalDiamonds == null || totalDiamonds == 0)){
			return;
		}
		log.error("methodName:repairOrderByNoCompute,当前日期={},订单金额相差={},开始修复...", dateStr,totalPrice);
		//查询订单数据
		List<OrderDay> list = orderDayMapper.getOrderDayList(startTime,endTime);
		if(CollectionUtils.isEmpty(list)){
			return;
		}
		for (OrderDay orderDay : list) {
			String bindChannelId = getBindChannelId(orderDay.getUserId());
			orderDay.setBindChannelId(bindChannelId);
		}
		log.warn("methodName:repairOrderByNoCompute,当前更新条数={},list={}", list.size(),JSON.toJSONString(list));
		//批量替换
		orderDayMapper.replaceBatchOrderDay(list);
	}

	/*//记录用户第一次充值
	private void doFirstOrder(PaymentOrder paymentOrder){
		LambdaQueryWrapper<FirstOrder> wrapper = new LambdaQueryWrapper();
//		.eq(FirstOrder::getCreateDate, paymentOrder.getCreateTime().toLocalDate())
		wrapper.eq(FirstOrder::getUserId, paymentOrder.getCliBuyerId()).orderByAsc(FirstOrder::getId).last("limit 1");
		FirstOrder record = firstOrderMapper.selectOne(wrapper);


		OrderDay firstPrice = orderDayMapper.getFirstPrice(paymentOrder.getCliBuyerId());
		if(firstPrice == null || firstPrice.getCliPrice() == null){
			return;
		}
		FirstOrder firstOrder = new FirstOrder();
		firstOrder.setUserId(paymentOrder.getCliBuyerId());
		firstOrder.setCliPrice(firstPrice.getCliPrice());
		firstOrder.setComputePrice(firstPrice.getComputePrice());
		firstOrder.setCreateTime(paymentOrder.getCreateTime());
		try {
			orderDayMapper.insertIgnoreFirstOrder(firstOrder);
		} catch (Exception e) {
			log.error("methodName:firstGiftRecord,param={},error={}", JSON.toJSONString(firstOrder), e.getMessage());
			e.printStackTrace();
		}
	}*/
}
